# -*- coding:utf-8 -*- #

# ----------------------------------------------------------
# Name:        test
# Description:
# Authon:      syl
# Date:        2020-12-09
# ----------------------------------------------------------
import requests
import threading
import time
import asyncio
import aiohttp
from concurrent.futures import ProcessPoolExecutor, as_completed


def test(i):
    data = {
        "Command": "query",
        "SubCommand": "status",
        "DeviceID": i
    }
    r = requests.post("http://127.0.0.1:6001/api/test3", json=data)
    print(r.content)


def mul_threading_resq():
    ths = []
    for i in range(10):
        t = threading.Thread(target=test, args=(i,))
        ths.append(t)
        t.start()
        print(f'{i}')
    for i in ths:
        i.join()


async def getjson(d):
    data = {
        "Command": "query",
        "SubCommand": "status",
        "DeviceID": d
    }
    async with aiohttp.request('POST', "http://127.0.0.1:6001/api/test", json=data) as r:
        resp = await r.json()
        # print(resp)
        return resp


async def work(datas, flag):
    ts = time.time()
    for d in datas:
        r = await getjson(d)
        print(f"{flag} {d} res :{r}")
    return f'{flag} {time.time() - ts}'


def asyncio_resq():
    datas = [i for i in range(100)]
    ts = time.time()
    datas = [datas[i * 10:(i + 1) * 10 if (i + 1) * 10 < 100 else 100] for i in range(10)]
    task = [work(d, i) for i, d in enumerate(datas)]
    loop = asyncio.get_event_loop()
    furures = loop.run_until_complete(asyncio.wait(task))
    for f in furures[0]:
        if f:
            print(f.result())


def p_handler(datas, pid):
    ts = time.time()
    count = len(datas)
    block = int(count / 10) + 1
    datas = [datas[i * block:(i + 1) * block if (i + 1) * 10 < count else count] for i in range(10)]
    task = [work(d, f'{pid}_{i}') for i, d in enumerate(datas)]
    loop = asyncio.get_event_loop()
    furures = loop.run_until_complete(asyncio.wait(task))
    for f in furures[0]:
        if f:
            print(f.result())
    return f'{pid} {time.time()-ts}'


def mul_p_async():
    datas = [i for i in range(1000)]
    ts = time.time()
    datas = [datas[i * 100:(i + 1) * 100 if (i + 1) * 100 < 1000 else 1000] for i in range(10)]

    executor = ProcessPoolExecutor(10)
    task = [executor.submit(p_handler, d, i) for i, d in enumerate(datas)]
    for t in as_completed(task):
        if t.done():
            print(t.result())
    print()


if __name__ == '__main__':
    ts = time.time()
    mul_p_async()
    print(f'cost {time.time() - ts}')
